using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.IO;
using System.Threading;
using System.Text;
using UnityEngine.UI;


public class TestWebServer : MonoBehaviour
{
    
    private HttpListener listener;
    
    // Start is called before the first frame update
    void Start()
    {
        listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
        Debug.Log("start");

        ThreadPool.QueueUserWorkItem((o) => {
            while(true) 
            {
                try
                {
                    var context = listener.GetContext();
                    ProcessRequest(context);

                }
                catch (Exception e)
                {
                    Debug.Log("Error"+ e.Message);
                }
            }
        });

    }

    private void ProcessRequest(HttpListenerContext context)
    {

        Debug.Log(context);
        string url = context.Request.Url.AbsolutePath;
        string httpMethod = context.Request.HttpMethod;
        HttpListenerRequest request = context.Request;

        if (url == "/assetbundle") {
            Debug.Log("Server get client asset bundle request");
            GetAssetBundle(context);
        } 
        else if (url == "/image") {
            Debug.Log("Server get client image request");
            GetTexture(context);
        } else if (url == "/text" && httpMethod == "GET")
        {
            Debug.Log("Server get client text request");
            GetText(context);
        } else if (url == "/text" && httpMethod == "POST")
        { 
            Debug.Log("Server post client text request");
            string txt = "hi there";
            using(Stream body = request.InputStream)
            using(StreamReader reader = new StreamReader(body, request.ContentEncoding))
            {
                string formData = reader.ReadToEnd();
                Debug.Log("Sever receive data:" + formData);
                string[] keypair = formData.Split("--");
                Debug.Log("Sever receive data:" + keypair[1]);
                string[] tempList = keypair[1].Split("=");
                Debug.Log("Sever receive data:" + tempList[2]);
                txt = tempList[2];
            }


            PostText(context, txt);
        }
    }

    private void GetText(HttpListenerContext context)
    {
        var response =  context.Response;
        string json = "{\"text\" : \" Hello World \"}";
        byte[] responseBuffer = Encoding.UTF8.GetBytes(json);

        response.ContentType = "application/json";
        response.ContentLength64 = responseBuffer.Length;

        var output = response.OutputStream;
        output.Write(responseBuffer, 0, responseBuffer.Length);
        output.Close();
    }


    private void PostText(HttpListenerContext context, string text)
    {
        var response = context.Response;
        string json = $"{text}";
        byte[] responseBuffer = Encoding.UTF8.GetBytes(json);
        response.ContentLength64 = responseBuffer.Length;
        var output = response.OutputStream;
        output.Write(responseBuffer, 0, responseBuffer.Length);
        output.Close();
    }

    private void GetTexture(HttpListenerContext context)
    {
        string imageName = "ServerData/image.JPG";
        string imagePath = Path.Combine(Application.dataPath, imageName);
        Debug.Log("image path:"+ imagePath);
        var response = context.Response;
        byte[] imageBytes = File.ReadAllBytes(imagePath);
        response.ContentType = "image/jpeg";
        response.ContentLength64 = imageBytes.Length;
        Stream output = response.OutputStream;
        output.Write(imageBytes, 0 , imageBytes.Length);
        output.Close();
    }

    private void GetAssetBundle(HttpListenerContext context)
    {
        string assetName = "ServerData/dlc_content.unity3d";
        string assetPath = Path.Combine(Application.dataPath, assetName);
        Debug.Log("server asset bundle path:" + assetPath);
        var response = context.Response;
        byte[] assetBytes = File.ReadAllBytes(assetPath);
        response.ContentType = "application/octet-stream";
        response.ContentLength64 = assetBytes.Length;
        Stream output = response.OutputStream;
        output.Write(assetBytes, 0, assetBytes.Length);
        output.Close();
    }


    void onDestroy()
    {
        listener.Stop();
        listener.Close();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
